//
//  SmallDecisionsXjdEditTemplateViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/7/26.
//

#import "SmallDecisionsXjdEditTemplateViewController.h"
#import "SmallDecisionsXjdEditTemplateItemCell.h"
#import "SmallDecisionsXjdTemplateTitleCell.h"
#import "SmallDecisionsXjdAddItemViewController.h"
#import "SmallDecisionsTextField.h"

@interface SmallDecisionsXjdEditTemplateViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *editTemplateTableView;

@end

@implementation SmallDecisionsXjdEditTemplateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"编辑";

    [self editTemplateTableView];
}

- (UITableView *)editTemplateTableView {
    if (!_editTemplateTableView) {
        _editTemplateTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _editTemplateTableView.delegate   = self;
        _editTemplateTableView.dataSource = self;
        _editTemplateTableView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_editTemplateTableView];
        _editTemplateTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_editTemplateTableView registerClass:[SmallDecisionsXjdEditTemplateItemCell class] forCellReuseIdentifier:@"SmallDecisionsXjdEditTemplateItemCellId"];
        [_editTemplateTableView registerClass:[SmallDecisionsXjdTemplateTitleCell class] forCellReuseIdentifier:@"SmallDecisionsXjdTemplateTitleCellId"];
        [_editTemplateTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.top.mas_equalTo(0);
        }];
    }
    return _editTemplateTableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return self.editModel.templateItems.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @weakify(self)
    if (indexPath.section == 0) {
        SmallDecisionsXjdTemplateTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SmallDecisionsXjdTemplateTitleCellId" forIndexPath:indexPath];
        cell.textField.text = self.editModel.templateTitle;
        [cell.templateTitleBtn setTitle:self.editModel.templateIcon forState:UIControlStateNormal];
        cell.textField.textFieldDidChangeAction = ^(SmallDecisionsTextField * _Nonnull textField, NSString * _Nullable text) {
            weak_self.editModel.templateTitle = text;
        };
        return cell;
    }

    SmallDecisionsXjdEditTemplateItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SmallDecisionsXjdEditTemplateItemCellId" forIndexPath:indexPath];
    cell.textField.text = self.editModel.templateItems[indexPath.row];
    cell.textField.textFieldDidChangeAction = ^(SmallDecisionsTextField * _Nonnull textField, NSString * _Nullable text) {
        weak_self.editModel.templateItems[indexPath.row] = text;
    };
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *tableViewHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"UITableViewHeaderViewID"];
    if (!tableViewHeaderView) {
        tableViewHeaderView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"UITableViewHeaderViewID"];
        UILabel *headerLabel = [[UILabel alloc] init];
        headerLabel.textColor = SmallDecisionsThemeFontColor;
        headerLabel.font = SmallDecisionsSetFontSize(14);
        headerLabel.tag = 1;
        [tableViewHeaderView.contentView addSubview:headerLabel];
        [headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(20);
            make.top.mas_equalTo(5);
        }];
    }

    UILabel *headerLabel = [tableViewHeaderView.contentView viewWithTag:1];
    if (section == 0) {
        headerLabel.text = @"问题";
    } else {
        headerLabel.text = @"选项";
    }
    tableViewHeaderView.contentView.backgroundColor = SmallDecisionsBgColor;
    return tableViewHeaderView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) return nil;
    UITableViewHeaderFooterView *tableViewFooterView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"UITableViewFooterViewID"];
    if (!tableViewFooterView) {
        tableViewFooterView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"UITableViewFooterViewID"];
        UIButton *addItemBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [addItemBtn setTitle:@"添加新选项" forState:UIControlStateNormal];
        [addItemBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        [addItemBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateHighlighted];
        addItemBtn.titleLabel.font = SmallDecisionsSetFontSize(17);
        addItemBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        [addItemBtn addTarget:self action:@selector(addItemBtnAction) forControlEvents:UIControlEventTouchUpInside];
        addItemBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [tableViewFooterView addSubview:addItemBtn];
        [addItemBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.height.mas_equalTo(30);
            make.top.mas_equalTo(10);
            make.width.mas_equalTo(120);
        }];
    }
    tableViewFooterView.contentView.backgroundColor = SmallDecisionsBgColor;
    return tableViewFooterView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 25;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) return 0.1;
    return 50;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *templateItems = [NSMutableArray arrayWithArray:self.editModel.templateItems];
    [templateItems removeObjectAtIndex:indexPath.row];
    self.editModel.templateItems = templateItems.copy;

    [tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    NSMutableArray *templateItems = [NSMutableArray arrayWithArray:self.editModel.templateItems];
    [templateItems exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    self.editModel.templateItems = templateItems.copy;
}

- (void)addItemBtnAction {
    SmallDecisionsXjdAddItemViewController *xjdAddItemVC = [[SmallDecisionsXjdAddItemViewController alloc] init];
    @weakify(self)
    xjdAddItemVC.callback = ^(NSArray *newItems) {
        if (newItems.count > 0) {
            NSMutableArray *templateItems = [NSMutableArray arrayWithArray:self.editModel.templateItems];
            [templateItems addObjectsFromArray:newItems];
            weak_self.editModel.templateItems = templateItems.copy;
            [weak_self.editTemplateTableView reloadData];
        }
    };
    [SmallDecisionsNavigatorManager presentViewController:xjdAddItemVC showNavigationBar:NO animationType:SmallDecisionsAnimationTypeAlert];
}

- (UIView *)setRightBarButton {
    UIButton *rightSaveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightSaveBtn setTitle:@"保存" forState:UIControlStateNormal];
    rightSaveBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
    [rightSaveBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
    rightSaveBtn.frame = CGRectMake(0, 0, 30, 30);
    return rightSaveBtn;
}

- (void)rightBarButtonAction:(UIButton *)view {
    if (self.callback) {
        self.callback(self.editModel);
    }
    [SmallDecisionsNavigatorManager popViewControllerAnimated:YES];
}

- (SmallDecisionsXjdModel *)editModel {
    if (!_editModel) {
        _editModel = [[SmallDecisionsXjdModel alloc] init];
        _editModel.templateIcon = @"🤔";
    }
    return _editModel;
}

@end
